package com.vshop.controller.other;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.vshop.entity.comentity.UserInfoReport;
import com.vshop.entity.interfacerequest.ExceptionRequest;
import com.vshop.entity.interfacerequest.querydevicecode.request.RequestQueryDeviceCode;
import com.vshop.entity.interfacerequest.querydevicecode.request.RequestQueryDeviceCodeData;
import com.vshop.entity.interfacerequest.querydevicecode.response.ResponseQueryDeviceCode;
import com.vshop.entity.interfacerequest.querydevicecode.response.ResponseQueryDeviceCodeData;
import com.vshop.entity.interfacerequest.querydevicecode.response.ResponseQueryDeviceCodeTradeData;
import com.vshop.service.SequenceService;
import com.vshop.service.UserInfoReportService;
import com.vshop.utils.Md5Encrypt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 根据openId查询deviceCode
 *
 * @author lm
 * @date 2019/03/07
 */
@RestController
@Api(description = "根据openId查询deviceCode")
@Slf4j
public class QueryDeviceCodeController {
    @Autowired
    private SequenceService sequenceService;

    @Autowired
    private UserInfoReportService userInfoReportService;

    @CrossOrigin
    @PostMapping(value = "queryDeviceCode", produces = "application/json;charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "根据openId查询deviceCode", response = ResponseQueryDeviceCode.class)
    public String queryDeviceCodeByOpenid(@ApiParam @RequestBody RequestQueryDeviceCode request) {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;

        ExceptionRequest utils = new ExceptionRequest();
        String requestStr = JSON.toJSONString(request);
        if (requestStr == null) {
            log.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            log.info("前端请求：" + requestStr);
            RequestQueryDeviceCode requestPackage = JSONArray.parseObject(requestStr, RequestQueryDeviceCode.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                log.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                log.info("请求的签名是：" + requestSign);
                RequestQueryDeviceCodeData requestData = requestPackage.getData();
                if (requestPackage.getData() == null) {
                    log.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String partnerCode = requestData.getPartnerCode();
                    String tradeTime = requestData.getTradeTime();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    String version = requestData.getVersion();
                    String openId = requestData.getOpenId();

                    if (StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(partnerCode) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(tradeType) || StringUtils.isBlank(openId) || lang == null || version == null) {
                        log.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        // 将请求体json转成String
                        String str = JSON.toJSONString(requestData);
                        // 将Str拿去计算签名
                        String sign = utils.calculateSignature(str);
                        log.info("计算的签名是：" + sign);
                        if (!requestSign.equalsIgnoreCase(sign)) {
                            log.info("签名验证失败！");
                            jsonString = utils.signatureFailure(ConnSeqNo, tradeTime, tradeType, "0001", "签名有误，请确认签名！");
                            return jsonString;
                        } else {//签名验证通过
                            //根据上发的openId去数据库查询并且返回
                            List<UserInfoReport> userList = userInfoReportService.queryDeviceCodeByOpenId(openId, partnerCode);
                            List<ResponseQueryDeviceCodeTradeData> tradeDataList = new ArrayList<ResponseQueryDeviceCodeTradeData>();
                            ResponseQueryDeviceCodeTradeData tradeData = null;

                            if (userList != null && !userList.isEmpty()) {

                                for (UserInfoReport u : userList) {
                                    String deviceCode = u.getDeviceCode();

                                    if (StringUtils.isNotBlank(deviceCode)) {
                                        String str1 = deviceCode.substring(0, 1);
                                        if (!str1.equals("卡") && !str1.equalsIgnoreCase("c")) {
                                            log.info("只返回有效的设备码：" + deviceCode);
                                            tradeData = new ResponseQueryDeviceCodeTradeData();
                                            tradeData.setOpenId(openId);
                                            tradeData.setDeviceCode(deviceCode);
                                            tradeDataList.add(tradeData);
                                        } else {
                                            continue;
                                        }

                                    } else {

                                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                                        return jsonString;

                                    }


                                }
                            }


                            ResponseQueryDeviceCodeData data = new ResponseQueryDeviceCodeData();
                            data.setConnSeqNo(ConnSeqNo);
                            data.setPartnerCode(partnerCode);
                            data.setTradeType(tradeType);
                            data.setTradeTime(tradeTime);
                            data.setTradeRstCode("0000");
                            data.setTradeData(tradeDataList);
                            if (lang.equals("cn") || StringUtils.isBlank(lang)) {
                                data.setTradeRstMessage("成功");
                            } else {
                                data.setTradeRstMessage("success");
                            }

                            ResponseQueryDeviceCode responseQueryDeviceCode = new ResponseQueryDeviceCode();
                            responseQueryDeviceCode.setData(data);
                            responseQueryDeviceCode.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));
                            jsonString = JSON.toJSONString(responseQueryDeviceCode);
                            log.info("响应报文：" + jsonString);
                            return jsonString;


                        }
                    }
                }
            }
        }
    }


}

